'''
在机器提起肺部轮廓的长宽后，可能存在部分病人的肺部轮廓提取偏差，
对机器提取结果逐张查看，对错误的提取结果执行手工重绘，保存结果

'''

import cv2
import os
import csv
import pydicom
import numpy as np
import pandas


def draw_rectangle(event, x, y, flags, param):
    global x1, y1, x2, y2
    if event == cv2.EVENT_LBUTTONDOWN:
        x1 = x
        y1 = y
    elif event == cv2.EVENT_LBUTTONUP:
        x2 = x
        y2 = y
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 1)

def read_img(path):
    pet_array = np.load(pet_path)
    pet_array = 1 - pet_array / (np.float(np.max(pet_array)))
    img = np.asarray(pet_array * 255, dtype=np.uint8)
    img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

    return img

if __name__ == '__main__':
    # 读取自动标注完成的文件
    data_path = 'D:/lung_cancer/data/all_data5.csv'
    data = []
    f = csv.reader(open(data_path, 'r'))
    for i in f:
        data.append(i)

    f = open('D:/lung_cancer/data/problem_for_center.txt')
    lines = f.readlines()
    for line in lines:
        patient = str(line.split(' ')[0])
        pet_path = 'D:/lung_cancer/data/Slice/origin_PETSlice/'+patient+'_PETSlice.npy'
        img = read_img(pet_path)
        cv2.imshow('origin', img)
        # img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        cv2.namedWindow('image')

        while(1):
            cv2.setMouseCallback('image', draw_rectangle)
            cv2.imshow('image', img)
            keycode = cv2.waitKey(1)

            # 刷新这张图像，重新标记病灶
            if keycode == ord('a'):
                img = read_img(pet_path)
                # img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
                cv2.destroyWindow('image')
                continue
            # 保存病灶坐标和半径
            elif keycode == ord('d'):
                for info in data[1:]:
                    if(str(info[1]) == patient):
                        info[46] = (x1+x2)//2
                        info[47] = (y1+y2)//2
                        info[48] = x2-x1
                        info[49] = y2-y1
                        print('%s-->center x:%d-->center y:%d-->w:%d-->h:%d'%(patient, (x1+x2)//2, (y1+y2)//2, x2-x1, y2-y1))
                break
        cv2.destroyAllWindows()

    df = pandas.DataFrame(data[1:], columns=data[0])
    df.to_csv('D:/lung_cancer/data/all_data6.csv', index=False)
